package cn.lili.modules.order.order.serviceimpl;

import cn.lili.modules.order.order.entity.dos.OrderFlow;
import cn.lili.modules.order.order.entity.dos.OrderItem;
import cn.lili.modules.order.order.entity.dos.OrderItemFlow;
import cn.lili.modules.order.order.entity.dto.OrderItemFlowSearchParams;
import cn.lili.modules.order.order.entity.vo.OrderItemFlowUserVO;
import cn.lili.modules.order.order.mapper.OrderItemFlowMapper;
import cn.lili.modules.order.order.service.OrderItemFlowService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 子单流水业务
 *
 * @author liushuai(liushuai711 @ gmail.com)
 * @version v4.0
 * @Description:
 * @since 2023/7/4 18:58
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderItemFlowServiceImpl extends ServiceImpl<OrderItemFlowMapper, OrderItemFlow> implements OrderItemFlowService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean generateOrderItemFlow(List<OrderItem> orderItems, OrderFlow orderFlow) {


        List<OrderItemFlow> orderItemFlows = new ArrayList<>(orderItems.size());

        for (OrderItem orderItem : orderItems) {
            orderItemFlows.add(new OrderItemFlow(orderFlow, orderItem));
        }

       return this.saveBatch(orderItemFlows);

    }

    @Override
    public OrderItemFlow getByOrderSnAndSkuId(String orderSn, String skuId) {
        LambdaQueryWrapper<OrderItemFlow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItemFlow::getOrderSn, orderSn);
        queryWrapper.eq(OrderItemFlow::getSkuId, skuId);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public Page<OrderItemFlowUserVO> getOrderFlowUserVOByCondition(OrderItemFlowSearchParams searchParams) {
        return this.baseMapper.getOrderFlowUserVOByCondition(PageUtil.initPage(searchParams), searchParams.getQueryWrapper());
    }

    @Override
    public Long amountOderFlowUserVOByCondition(OrderItemFlowSearchParams searchParams) {
        Long amount = this.baseMapper.amountOderFlowUserVOByCondition(searchParams.getQueryWrapper());
        return amount == null ? 0L : amount;

    }
}
